<template>
  <a-modal v-model:open="visible" :title="isEdit ? '编辑分类' : '添加分类'" :ok-text="isEdit ? '更新' : '创建'" cancel-text="取消" @ok="handleSubmit" @cancel="handleCancel" :confirm-loading="loading" width="500px">
    <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical" autocomplete="off">
      <a-form-item label="分类标题" name="title">
        <a-input v-model:value="formData.title" placeholder="请输入分类标题" :maxlength="50" />
      </a-form-item>

      <a-form-item label="分类描述" name="description">
        <a-textarea v-model:value="formData.description" placeholder="请输入分类描述（可选）" :rows="3" :maxlength="200" show-count />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { message } from 'ant-design-vue'
import { createIllustrationCategory, updateIllustrationCategory } from '@/utils/api'

const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  categoryData: {
    type: Object,
    default: () => null
  }
})

const emit = defineEmits(['update:open', 'success'])

// 控制弹窗显示
const visible = ref(false)
const loading = ref(false)
const formRef = ref()

// 判断是否为编辑模式
const isEdit = ref(false)

// 表单数据
const formData = reactive({
  title: '',
  description: ''
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入分类标题', trigger: 'blur' },
    { min: 1, max: 50, message: '标题长度应在1-50字符之间', trigger: 'blur' }
  ],
  description: [{ max: 200, message: '描述长度不能超过200字符', trigger: 'blur' }]
}

// 监听弹窗开关
watch(
  () => props.open,
  (newVal) => {
    visible.value = newVal
    if (newVal) {
      initForm()
    }
  }
)

watch(visible, (newVal) => {
  emit('update:open', newVal)
})

/**
 * 初始化表单数据
 */
const initForm = () => {
  if (props.categoryData) {
    // 编辑模式
    isEdit.value = true
    formData.title = props.categoryData.title || ''
    formData.description = props.categoryData.description || ''
  } else {
    // 新增模式
    isEdit.value = false
    formData.title = ''
    formData.description = ''
  }
}

/**
 * 提交表单
 */
const handleSubmit = async () => {
  try {
    // 验证表单
    await formRef.value.validateFields()

    loading.value = true

    if (isEdit.value) {
      // 更新分类
      await updateIllustrationCategory(props.categoryData.id, {
        title: formData.title.trim(),
        description: formData.description.trim()
      })
      message.success('分类更新成功')
    } else {
      // 创建分类
      await createIllustrationCategory({
        title: formData.title.trim(),
        description: formData.description.trim()
      })
      message.success('分类创建成功')
    }

    // 通知父组件刷新数据
    emit('success')

    // 关闭弹窗
    visible.value = false
  } catch (error) {
    console.error('操作失败:', error)
    message.error(error.message || '操作失败')
  } finally {
    loading.value = false
  }
}

/**
 * 取消操作
 */
const handleCancel = () => {
  visible.value = false

  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields()
  }
}
</script>

<style scoped>
.ant-form-item {
  margin-bottom: 16px;
}
</style>
